﻿/************************************************************************
* Copyright (c) 2018 All Rights Reserved.
*命名空间：AOP.Filter.Login
*文件名： LoginFilterAttribute
*创建人： kingling
*创建时间：2018/7/5 11:34:51
*描述
*=======================================================================
*修改标记
*修改时间：2018/7/5 11:34:51
*修改人：kingling
*描述：
************************************************************************/

using AOP.Filter.Result;
using CacheService.Standard;
using Common.Standard;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Text;

namespace AOP.Filter.Login
{
    public class LoginFilterAttribute : IActionFilter
    {
        ICache cache;
        public LoginFilterAttribute(ICache cache)
        {
            this.cache = cache;
        }
        public void OnActionExecuted(ActionExecutedContext context)
        {
            //throw new NotImplementedException();
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            var actiondescriptor = context.ActionDescriptor as ControllerActionDescriptor;
            //控制器上是否有过滤标签
            var no_login_controller = context.Controller.GetType().IsDefined(typeof(NoLoginAttribute), true);
            if (no_login_controller)
            {
                return;
            }
            //控制器上是否有过滤标签
            var no_login_action = actiondescriptor.MethodInfo.IsDefined(typeof(NoLoginAttribute), true);
            if (no_login_action)
            {
                return;
            }
            var key = context.HttpContext.Request.Cookies["key"];
            if (string.IsNullOrWhiteSpace(key)|| cache.get<object>(key)==null)
            {
                if (actiondescriptor.MethodInfo.ReturnType.Name == "IActionResult")
                {
                    context.Result = new RedirectResult("/login");
                }
                else
                {
                    throw new Error("用户尚未登录");
                }
                return;
            }            
        }
    }
}
